﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Controllers
{
	using System.Web.Mvc;
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Enums;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Domain.Values;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation;
	using Falcon.Core.ViewModels;

	[Authorize]
	public class SystemUserController : DefaultController
	{
		public SystemUserController(
			IUserService userService,
			IUserRoleService userRoleService,
			IUserPermissionService userPermissionService)
		{
			this.UserService = userService;
			this.UserRoleService = userRoleService;
			this.UserPermissionService = userPermissionService;
		}

		public IUserService UserService
		{
			get;
			private set;
		}

		public IUserRoleService UserRoleService
		{
			get;
			private set;
		}

		public IUserPermissionService UserPermissionService
		{
			get;
			private set;
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Index(string status, SortUser sort, SortOrder order, int? page)
		{
			var users = UserService.GetPaged(new UserSpecification
			{
				Status = status.AsEnum<UserStatus>(),
				Sort = sort,
				Order = order,
				Page = page,
				Limit = Settings.Users.PageLimit
			});

			var user = users.FirstOrDefault();

			return user.CanUpdateAny ? View(Views.Index, Masters.System, users) : NotAuthorized();
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Create()
		{
			var user = UserService.Create();

			return user.CanUpdateAny ? View(Views.Create, Masters.System, new UserCreate()) : NotAuthorized();
		}

		[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
		public ActionResult Create(UserCreate value)
		{
			try
			{
				var user = UserService.Create();

				if (!user.CanUpdateAny)
				{
					return NotAuthorized();
				}

				UserService.Insert(user, value);

				return Message(Routes.SystemUserUpdate, new { id = user.Id }, Resources.Messages.UserCreated.Fmt(user.Name));
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Create, Masters.System, value);
		}

		[AcceptVerbs(HttpVerbs.Get), Authorize]
		public ActionResult Update(int id)
		{
			var user = UserService.GetById(id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			return user.CanUpdateAny ? View(Views.Update, Masters.System, new UserUpdate(user)) : NotAuthorized();
		}

		[AcceptVerbs(HttpVerbs.Post), Authorize, ValidateAntiForgeryToken]
		public ActionResult Update(UserUpdate value)
		{
			try
			{
				var user = UserService.GetById(value.Id);

				if (user == null)
				{
					return Error(Resources.Messages.UserNotFound);
				}

				if (!user.CanUpdateAny)
				{
					return NotAuthorized();
				}

				UserService.Update(user, value);

				return Message(Routes.SystemUserUpdate, new { id = user.Id }, Resources.Messages.UserUpdated.Fmt(user.Name));
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Update, Masters.System, value);
		}

		[AcceptVerbs(HttpVerbs.Get), Authorize]
		public ActionResult Delete(int id)
		{
			var user = UserService.GetById(id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			return user.CanDeleteAny ? View(Views.Delete, Masters.System, new UserDelete(user)) : NotAuthorized();
		}

		[AcceptVerbs(HttpVerbs.Post), Authorize, ValidateAntiForgeryToken]
		public ActionResult Delete(UserDelete value)
		{
			try
			{
				var user = UserService.GetById(value.Id);

				if (user == null)
				{
					return Error(Resources.Messages.UserNotFound);
				}

				if (!user.CanDeleteAny)
				{
					return NotAuthorized();
				}

				UserService.Delete(user);

				return RedirectToRoute(Routes.SystemUserIndex);
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Delete, Masters.System, value);
		}

		[AcceptVerbs(HttpVerbs.Get), Authorize]
		public ActionResult Permission(int id)
		{
			var user = UserService.GetById(id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			if (!user.CanUpdateAny)
			{
				return NotAuthorized();
			}

			// get roles
			var roles = UserRoleService.GetAll();

			// get permissions for user
			var permissions = UserPermissionService.GetGrouped(new UserPermissionSpecification
			{
				UserId = user.Id
			});

			var model = new UserPermissionViewModel
			{
				User = user,
				Roles = roles,
				Permissions = permissions
			};

			return View(Views.Permission, Masters.System, model);
		}

		[AcceptVerbs(HttpVerbs.Post), Authorize]
		public ActionResult Permission(int id, UserPermissionUpdate[] values)
		{
			var user = UserService.GetById(id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			if (!user.CanUpdateAny)
			{
				return NotAuthorized();
			}

			UserPermissionService.Update(user, values);

			return RedirectToRoute(Routes.SystemUserPermission, new { id = user.Id });
		}
	}
}